package cn.team11.sds.dayi.debugpage;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import cn.team11.sds.dayi.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.aliyun.alink.utils.ALog;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class BindTaobaoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_taobao);
        Intent i = getIntent();
        String data = i.getDataString();
        Uri url = Uri.parse(data);
        String code = url.getQueryParameter("code");
        String state = url.getQueryParameter("state");
        if ("100".equals(state)) {
            QueryAccessToken (code);
        } else if ("200".equals(state)) {

        }
    }

    void QueryAccessToken (final String code)
    {
        Thread t = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                ALog.d("t11","dddddddddddddddddddddddddd");
                Map<String, Object> params = new HashMap<>();
                params.put("code", code);
                params.put("grant_type", "authorization_code");
                params.put("client_id", "24539636");
//                params.put("client_id", "23813603");
                params.put("client_secret", "daedf9dfb4e0e129b22c220f908000ac");
//                params.put("redirect_uri", "tboauthopen23813603://openalink/");
                params.put("redirect_uri", "tboauthopen24539636://openalink/");
                params.put("state", "200");
                params.put("view", "wap");

                String jsonstr = postUrlConnect("https://oauth.taobao.com/token", params);
                if (!TextUtils.isEmpty(jsonstr)) {
                    JSONObject jsonObj = JSON.parseObject(jsonstr);
                    if (jsonObj != null) {

                        TransitoryRequest transitoryRequest = new TransitoryRequest();
                        transitoryRequest.setMethod("mtop.openalink.user.third.account.link");
                        transitoryRequest.putParam("accessToken", jsonObj.getString("access_token"));
                        transitoryRequest.putParam("userId", "ddddd");
                        transitoryRequest.putParam("userNick", "yuqing");
                        transitoryRequest.putParam("type", "cs");
                        transitoryRequest.putOpts("post", "1");

                        ALinkBusinessEx biz = new ALinkBusinessEx();
                        biz.request(transitoryRequest, new ALinkBusinessEx.IListener() {
                            @Override
                            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                                Log.i("BindTaobaoActivity", "onSuccess");
                            }

                            @Override
                            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                                Log.i("BindTaobaoActivity", "onFailed");
                            }
                        });
                    }
                }
            }
        });
        t.start();
    }

    static String postUrlConnect(String urlPath, Map<String,Object> map){
        StringBuffer sbRequest =new StringBuffer();
        if(map!=null&&map.size()>0){
            for (String key:map.keySet()){
                sbRequest.append(key+"="+map.get(key)+"&");
            }
        }
        String request = sbRequest.substring(0,sbRequest.length()-1);
        try {
            //创建URL
            URL url = new URL(urlPath);
            //由URL的openConnection方法得到一个HttpURLConnection
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //设置post提交
            httpURLConnection.setRequestMethod("POST");
            //设置超时时间
            httpURLConnection.setConnectTimeout(30000);
            httpURLConnection.setReadTimeout(30000);

            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);

            //把请求正文通过OutputStream发出去
            OutputStream os =httpURLConnection.getOutputStream();
            os.write(request.getBytes());
            os.flush();

            //判断响应码  200 代表成功
            if(httpURLConnection.getResponseCode()==200){
                //由HttpURLConnection拿到输入流
                InputStream in=httpURLConnection.getInputStream();
                StringBuffer sb=new StringBuffer();
                //根据输入流做一些IO操作
                byte [] buff =new byte[1024];
                int len=-1;
                while((len=in.read(buff))!=-1){
                    sb.append(new String(buff,0,len,"utf-8"));
                }

                in.close();
                os.close();
                httpURLConnection.disconnect();
                return  sb.toString();
            }else{
                return null;
            }

        }catch (Exception e){
            Log.e("post","code:"+e.getMessage());
            return null;
        }
    }
}
